import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../components/login.vue'
import home from '../components/home.vue'
import welcome from '../components/welcome.vue'
import users from '../components/user/users.vue'
import rights from '../components/power/rights.vue'
import roles from '../components/power/roles.vue'
import cate from '../components/goods/cate.vue'
import params from '../components/goods/params.vue'
import GoodsList from '../components/goods/list.vue'
import addGoods from '../components/goods/add.vue'
import orders from '../components/order/order.vue'
import report from '../components/report/report.vue'
Vue.use(VueRouter)   //注册全局中间件

const routes = [
  //路由重定向 当访问根路径的时候自动跳转到login页面
  { path: '/', redirect: '/login' },
  //当我们访问login的时候 就显示login组件里面的代码
  { path: '/login', component: login },
  {
    path: '/home',
    component: home,
    redirect: '/welcome',     //当访问home主页的时候就自动跳转到welcome子组件
    children: [
      { path: '/welcome', component: welcome },
      { path: '/users', component: users },
      { path: '/rights', component: rights },
      { path: '/roles', component: roles },
      { path: '/categories', component: cate },
      { path: '/params', component: params },
      { path: '/goods', component: GoodsList },
      { path: '/goods/add', component: addGoods },
      { path: '/orders', component: orders },
      { path: '/reports', component: report },
    ]
  }
]

const router = new VueRouter({
  routes
})

//挂载路由导航守卫,负责监视用户是否用token登录,如果不是用的token值登录的话,就必须跳转到登录页面
//to 将要访问的页面, from 从那个页面跳转而来的 next 放行函数 next() 或则 next('/跳转的页面)
router.beforeEach((to, from, next) => {
  //如果用户将要访问 login页面 , 而登录页面不需要token值就可以访问, 所以直接放行
  if (to.path == '/login') return next()
  //如果访问的不是登录页面,说明要token值, 所以需要进行是否有token值判断,如果有,就可以继续浏览,没有就立即返回到登录页面
  //获取token值
  const token = window.sessionStorage.getItem('token')
  if (!token) return next('/login') //没有token值就返回登录页面
  next()
})
export default router
